package com.christina.engine.routing.manager;

import com.christina.engine.intent.model.Intent;
import com.christina.engine.processing.model.ProcessingContext;
import com.christina.engine.routing.model.RoutingDecision;
import com.christina.engine.routing.strategy.RoutingStrategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import jakarta.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 默认路由策略管理器实现
 * 负责策略的注册、选择和执行机制
 *
 * @author Christina
 */
@Slf4j
@Component
public class DefaultRoutingStrategyManager implements RoutingStrategyManager {
    
    // 存储已注册的路由策略
    private final List<RoutingStrategy> strategies = new ArrayList<>();
    
    @Override
    public void registerStrategy(RoutingStrategy strategy) {
        if (strategy == null) {
            throw new IllegalArgumentException("Routing strategy cannot be null");
        }
        
        // 避免重复注册
        if (strategies.stream().noneMatch(s -> s.getClass().equals(strategy.getClass()))) {
            strategies.add(strategy);
            sortStrategiesByPriority();
            log.info("Registered routing strategy: {}, priority: {}", 
                     strategy.getClass().getSimpleName(), strategy.getPriority());
        }
    }
    
    @Override
    public void unregisterStrategy(RoutingStrategy strategy) {
        if (strategy != null) {
            strategies.remove(strategy);
            log.info("Unregistered routing strategy: {}", 
                     strategy.getClass().getSimpleName());
        }
    }
    
    @Override
    public List<RoutingStrategy> getRegisteredStrategies() {
        return new ArrayList<>(strategies);
    }
    
    @Override
    public RoutingStrategy selectStrategy(Intent intent, ProcessingContext context) {
        if (intent == null) {
            throw new IllegalArgumentException("Intent cannot be null");
        }
        
        // 优先选择优先级高且支持该意图的策略
        for (RoutingStrategy strategy : strategies) {
            if (strategy.supports(intent)) {
                log.debug("Selected routing strategy: {} for intent: {}", 
                         strategy.getClass().getSimpleName(), intent.getType());
                return strategy;
            }
        }
        
        log.warn("No routing strategy supports intent: {}", intent.getType());
        return null;
    }
    
    @Override
    public RoutingDecision makeRoutingDecision(Intent intent, ProcessingContext context) {
        if (intent == null) {
            throw new IllegalArgumentException("Intent cannot be null");
        }
        
        RoutingStrategy strategy = selectStrategy(intent, context);
        if (strategy != null) {
            try {
                RoutingDecision decision = strategy.route(intent, context);
                log.debug("Routing decision made: {} -> {}, confidence: {}", 
                         intent.getType(), decision.getTargetService(), decision.getConfidence());
                return decision;
            } catch (Exception e) {
                log.error("Error executing routing strategy: {}", 
                          strategy.getClass().getSimpleName(), e);
            }
        }
        
        // 如果没有找到合适的策略或执行失败，返回默认决策
        String defaultService = getDefaultServiceForIntent(intent);
        log.warn("Using default routing for intent: {} -> {}", intent.getType(), defaultService);
        return RoutingDecision.defaultDecision(defaultService);
    }
    
    @Override
    public void sortStrategiesByPriority() {
        // 按照优先级升序排序（优先级数值越小，优先级越高）
        strategies.sort(Comparator.comparingInt(RoutingStrategy::getPriority));
    }
    
    /**
     * 根据意图类型获取默认服务
     * 这是一个简单的兜底机制
     */
    private String getDefaultServiceForIntent(Intent intent) {
        switch (intent.getType()) {
            case TRAVEL_PLANNING, TRAVEL_BOOKING, TRAVEL_INQUIRY, TRAVEL_MODIFICATION, TRAVEL_CANCELLATION:
                return "travel";
            case GENERAL_CHAT, QUESTION_ANSWER, RECOMMENDATION:
                return "chat";
            case USER_REGISTRATION, USER_LOGIN, USER_PROFILE:
                return "user";
            default:
                return "fallback";
        }
    }
    
    /**
     * 初始化时自动排序
     */
    @PostConstruct
    public void init() {
        sortStrategiesByPriority();
        log.info("Routing strategy manager initialized with {} strategies", strategies.size());
    }
}